STRINGS
a string is a sequence of characters. C# strings are objects of the built-in string data type. Thus, string is a reference type. Moreover, string is C#’s name for System.String. Once a string has been created, the character sequence that comprises a string cannot be altered. This restriction allows C# to implement strings more efficiently.
To create a string that can be changed, C# offers a class called StringBuilder, which is in the System.Text namespace. For most purposes, however, you will want to use string, not StringBuilder.
String is defined in the System namespace. It implements the IComparable, IComparable<string>, ICloneable, IEquatable<string>, IConvertible, IEnumerable and IEnumerable<string> interfaces. String is a sealed class.
Constructors

public String(char[ ] chrs)
public String(char[ ] chrs, int start, int count)
public String(char ch, int count)
 
public String(char* chrs)
public String(char* chrs, int start, int count)
public String(sbyte* chrs)
public String(sbyte* chrs, int start, int count)
public String(sbyte* chrs, int start, int count, Encoding en)

String Methods


Method

What It Does

Clone

Returns a reference to the instance of the string.

CompareTo

Compares this string with another.

CopyTo

Copies the specified number of characters from the string instance to a char array.

EndsWith

Returns true if the specified string matches the end of the instance string.

Equals

Determines whether the instance string and a specified string have the same value.

GetEnumerator

Method required to support the IEnumerator interface.

IndexOf

Reports the index of the first occurrence of a specified character or string within the instance.

Insert

Returns a new string with the specified string inserted at the specified position in the current string.

LastIndexOf

Reports the index of the last occurrence of a specified character or string within the instance.

PadLeft

Returns a new string with the characters in this instance right-aligned by padding on the left with spaces or a specified character for a specified total length.

PadRight

Returns a new string with the characters in this instance left-aligned by padding on the right with spaces or a specified character for a specified total length.

Remove

Returns a new string that deletes a specified number of characters from the current instance beginning at a specified position.

Replace

Returns a new string that replaces all occurrences of a specified character or string in the current instance, with another character or string.

Split

Identifies the substrings in this instance that are delimited by one or more characters specified in an array, then places the substrings into a string array.

StartsWith

Returns true if the specified string matches the beginning of the instance string.

Substring

Returns a substring from the instance.

ToCharArray

Copies the characters in the instance to a character array.

ToLower

Returns a copy of the instance in lowercase.

ToUpper

Returns a copy of the instance in uppercase.

Trim

Returns a copy of the instance with all occurrences of a set of specified characters from the beginning and end removed.

TrimEnd

Returns a copy of the instance with all occurrences of a set of specified characters at the end removed.

TrimStart

Returns a copy of the instance with all occurrences of a set of specified characters from the beginning removed.

static methods of the String class.

Method

What It Does

Compare

Compares two string objects.

CompareOrdinal

Compares two string objects without considering the local national language or culture.

Concat

Creates a new string by concatenating one or more strings.

Copy

Creates a new instance of a string by copying an existing instance.

Format

Formats a string using a format specification. format specifications are several.

Join

Concatenates a specified string between each element in a string to yield a single concatenated string.

Numeric Format Specifiers


Specifier

Format

Meaning of Precision Specifier

C

Currency (that is, a monetary value).

Specifies the number of decimal places.

c

Same as C.

 

D

Whole number numeric data. (Use with integers only.)

Minimum number of digits. Leading zeros will be used to pad the result, if necessary.

d

Same as D.

 

E

Scientific notation (uses uppercase E).

Specifies the number of decimal places. The default is six.

e

Scientific notation (uses lowercase e).

Specifies the number of decimal places. The default is six.

F

Fixed-point notation.

Specifies the number of decimal places.

f

Same as F.

 

G

Use either E or F format, whichever is shorter.

See E and F.

g

Use either e or f format, whichever is shorter.

See e and f.

N

Fixed-point notation, with comma separators.

Specifies the number of decimal places.

n

Same as N.

 

P

Percentage.

Specifies the number of decimal places.

p

Same as P.

 

R

Numeric value that can be parsed, using Parse( ), back into its equivalent internal form. (This is called the “round-trip” format.)

Not used.

r

Same as R.

 

X

Hexadecimal (uses uppercase letters A through F).

Minimum number of digits. Leading zeros will be used to pad the result, if necessary.

x

Hexadecimal (uses lowercase letters a through f).

Minimum number of digits. Leading zeros will be used to pad the result if necessary.

 

Program on Constructors
using System;
namespace strings
{
class Program
{
static void Main(string[] args)
{

char[] a = { 'v', 'i', 's', 'i', 'o', 'n' };
String s = new String(a);
Console.WriteLine(s);
String s1 = new String(a, 2, 3);
Console.WriteLine(s1);
String s2 = new String('V', 5); // V repeats 5 times
Console.WriteLine(s2);

}
}
}
Program on String Class Methods
using System;

 

namespace strings
{
class Program
{
static void Main(string[] args)
{
String k = "Vision";
String k1 = (String)k.Clone();// explicit conversion is mandatory
Console.WriteLine(k1);

if (k.CompareTo(k1) == 0)
Console.WriteLine("Both are equal");
else
Console.WriteLine("Not Equal strings");

char []a=new char[k1.Length +1];
k1.CopyTo(0, a, 0,k1.Length );
Console.WriteLine(a);

Console.WriteLine (k1.EndsWith ("n"));
Console.WriteLine(k1.StartsWith("p"));
if (k1.Equals(k) == true)
Console.WriteLine("Both are equal");
else
Console.WriteLine("Not Equal");

          Console.WriteLine(k1.IndexOf("s"));
Console.WriteLine (k1.LastIndexOf ("i"));
String k2=k1.Insert(3, "PrasaD");
Console.WriteLine(k2);
String p = k.PadLeft(20);
Console.WriteLine(p);
String p1 = k.PadLeft(20, '#');
Console.WriteLine(p1);
String p2 = k.PadRight(20, '*');
Console.WriteLine(p2);
String p3 = k1.Remove(3);
Console.WriteLine(p3);
String p4 = k1.Remove(3, 1);
Console.WriteLine(p4);
String p5 = k1.Replace('i', 'p');
Console.WriteLine(p5);
char[] deli = { '.', ',', ':' };
String p6="Welcome. To vison. Computers, are the : one of the, Important";
String[] p7 = p6.Split(deli);
for (int i = 0; i < p7.Length; i++)
Console.WriteLine(p7[i]);
Console.WriteLine(k.Substring(4));
Console.WriteLine(k.Substring(3, 2));
char[] c1 = k.ToCharArray();
Console.WriteLine(c1);
Console.WriteLine(k.ToLower());
Console.WriteLine(k.ToUpper());

String p8="     Vision    ";
String p9 = p8.Trim();
Console.WriteLine(p9);
Console.WriteLine(String.Compare("Prasad", "Prasad"));
String p10 = String.Concat("PrasaD", "Vision");
Console.WriteLine(p10);
double d = 10.4564;

            String p11 = String.Format("{0:E}", d); // 0:E format sets the scientific notation
Console.WriteLine(p11);
String p111 = d.ToString("C"); // preceds $ curency sign
Console.WriteLine(p111);

            String []p12={"prasaD","vision","murali","Vamsi","Gautam"};

            // Concatinates the all string seperated by -
String p13 = String.Join("-", p12);
Console.WriteLine(p13);

        }
}
}

Formatting Date and Time

Addition to formatting numeric values, another data type to which formatting is often applied is DateTime. DateTime represents date and time. C# provides an extensive formatting subsystem for time and date values.


Specifier

Format

D

Date in long form.

d

Date in short form.

F

Date and time in long form.

f

Date and time in short form.

G

Date in short form, time in long form.

g

Date in short form, time in short form.

M

Month and day.

m

Same as M.

R

Date and time in standard, GMT form.

r

Same as R.

s

A sortable form of date and time.

T

Time in long form.

t

Time in short form.

U

Long form, universal form of date and time. Time is displayed as UTC.

u

Short form, universal form of date and time.

Y

Month and year.

y

Same as Y.

Program on DateTime Format

using System;

class Sample
{
public static void Main()
{
DateTime dt = DateTime.Now; // obtain current time

        Console.WriteLine("d format: {0:d}", dt);
Console.WriteLine("D format: {0:D}", dt);

        Console.WriteLine("t format: {0:t}", dt);
Console.WriteLine("T format: {0:T}", dt);

        Console.WriteLine("f format: {0:f}", dt);
Console.WriteLine("F format: {0:F}", dt);

        Console.WriteLine("g format: {0:g}", dt);
Console.WriteLine("G format: {0:G}", dt);

        Console.WriteLine("m format: {0:m}", dt);
Console.WriteLine("M format: {0:M}", dt);

        Console.WriteLine("r format: {0:r}", dt);
Console.WriteLine("R format: {0:R}", dt);

        Console.WriteLine("s format: {0:s}", dt);

        Console.WriteLine("u format: {0:u}", dt);
Console.WriteLine("U format: {0:U}", dt);

        Console.WriteLine("y format: {0:y}", dt);
Console.WriteLine("Y format: {0:Y}", dt);
}
}